package legumes.client.ui.widgets.form.item;

import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.validator.CustomValidator;
import com.smartgwt.client.widgets.form.validator.IsStringValidator;
import com.smartgwt.client.widgets.form.validator.LengthRangeValidator;

public class PlaceDeliveryFormItem extends TextItem {

	private String [] placesAlreadyCreated;
	
	public PlaceDeliveryFormItem(String [] placesAlreadyCreated_){
		super("PlaceDeliveryFormItem", "Nom du lieu de livraison");
		placesAlreadyCreated = placesAlreadyCreated_;
		setShowTitle(true);
		setHint("<i>Exemple : 'Salarie de l'entreprise XYZ.'</i>");
		setWidth(200);
		setTextAlign(Alignment.LEFT);
		setValidateOnExit(true);
		setValidateOnChange(true);
		
		LengthRangeValidator lrv = new LengthRangeValidator();
        lrv.setMin(1);
        lrv.setMax(100);
        lrv.setErrorMessage("Saisir un nom entre 1 et 100 charact&egrave;res.");
        
        IsStringValidator isStringValidator = new IsStringValidator();
        isStringValidator.setErrorMessage("Veuillez saisir une chaines de caract&egrave;res.");

        CustomValidator cv = new CustomValidator(){

			@Override
			protected boolean condition(Object value) {
				return value instanceof String && 
				value != null &&
				((String)value).trim().length()>0;
			}
        	
        };
        cv.setErrorMessage("Veuillez saisir au moins un caractère.");
        
        CustomValidator cv2 = new CustomValidator(){

			@Override
			protected boolean condition(Object value) {
				int i=0;
				while(placesAlreadyCreated!= null 
						&& placesAlreadyCreated.length>0 
						&& i<placesAlreadyCreated.length
						&& !((String)value).equalsIgnoreCase(placesAlreadyCreated[i]) ){
					i++;
				}
				return placesAlreadyCreated!= null && i>=placesAlreadyCreated.length;
			}
        	
        };
        cv.setErrorMessage("Ce nom existe déjà; veuillez saisir un nom différent.");

        setValidators(isStringValidator, lrv, cv, cv2);
	}

	public String[] getPlacesAlreadyCreated() {
		return placesAlreadyCreated;
	}

	public void setPlacesAlreadyCreated(String[] placesAlreadyCreated) {
		this.placesAlreadyCreated = placesAlreadyCreated;
	}
	
	
}
